package com.zzh.takeoutapp.view;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.ScreenAdapter;
import com.zzh.takeoutapp.adapter.Tag2Adapter;
import com.zzh.takeoutapp.adapter.TagAdapter;
import com.zzh.takeoutapp.config.UrlConfig;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.SPUtils;
import com.zzh.takeoutapp.view.folw.FlowTagLayout;
import com.zzh.takeoutapp.view.folw.OnTagClickListener;
import com.zzh.takeoutapp.view.folw.OnTagSelectListener;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/24.
 */

public class FilterView extends LinearLayout implements View.OnClickListener, OnTagSelectListener, OnTagClickListener {
    @Bind(R.id.ll_content_list_view)
    LinearLayout llContentListView;
    @Bind(R.id.tv_comprehensive)
    LinearLayout tv_comprehensive;//综合排序
    @Bind(R.id.view_mask_bg)
    View viewMaskBg;
    @Bind(R.id.iv_category_arrow)
    ImageView ivCategoryArrow;
    @Bind(R.id.home_sales_volume)
    TextView tvHomeSalesVolume;//销量
    @Bind(R.id.home_distance)
    TextView tvHomeDistance;//距离
    @Bind(R.id.home_screen)
    LinearLayout lvHomeScreen;
    @Bind(R.id.home_iv_screen)
    ImageView ivHomeScreen;
    @Bind(R.id.lv_left)
    ListView lvLeft;
    @Bind(R.id.screen_select)
    LinearLayout screenSelect;
    @Bind(R.id.size_flow_layout)
    FlowTagLayout mSizeFlowLayout;
    @Bind(R.id.history_flow_layout)
    FlowTagLayout mHistoryFlowLayout;
    @Bind(R.id.tv_clear)
    TextView tv_clear;
    @Bind(R.id.tv_affirm)
    TextView tv_affirm;
    private TagAdapter<String> mSizeTagAdapter;
    private Tag2Adapter<String> tag2Adapter;
    public static final String HOMESALESVOLUME = "tvHomeSalesVolume";
    public static final String HOMEDISTANCE = "tvHomeDistance";
    public static final String HOMESCREEN = "lvHomeScreen";
    private boolean isScreen;
    private int filterPosition = -1;
    private int screenPosition;
    private Context mContext;
    private boolean isShowing = false;
    private int lastFilterPosition = -1;
    public static final int POSITION_CATEGORY = 0; // 分类的位置
    public static final int POSITION_SORT = 1; // 排序的位置
    public static final int POSITION_FILTER = 2; // 筛选的位置
    private int panelHeight;
    private List<String> getKey;//选择优惠的选项
    private List<String> getKeytag2;//选择优惠的选项
    private List<String> selectKey;
    private final String ON_ITEM_CLICK = "onItemClick";//listView
    private final String YOU_HUI_FILTER = "youhui_filter";
    private final String PEI_FILTER = "pei_filter";
    public Map<String, String> SizeTaglist;
    public Map<String, String> Historylist;
    public Map<String, String> tag2list;
    public TextView getTvHomeSalesVolume() {
        return tvHomeSalesVolume;
    }

    public void setTvHomeSalesVolume(TextView tvHomeSalesVolume) {
        this.tvHomeSalesVolume = tvHomeSalesVolume;
    }

    public TextView getTvHomeDistance() {
        return tvHomeDistance;
    }

    public void setTvHomeDistance(TextView tvHomeDistance) {
        this.tvHomeDistance = tvHomeDistance;
    }
    public Map<String, String> getSizeTaglist() {
        return SizeTaglist;
    }

    public void setSizeTaglist(Map<String, String> sizeTaglist) {
        SizeTaglist = sizeTaglist;
    }

    public Map<String, String> getHistorylist() {
        return Historylist;
    }

    public void setHistorylist(Map<String, String> historylist) {
        Historylist = historylist;
    }

    public Map<String, String> getTag2list() {
        return tag2list;
    }

    public void setTag2list(Map<String, String> tag2list) {
        this.tag2list = tag2list;
    }

    public FilterView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init(context);
    }

    public FilterView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        selectKey = new ArrayList<>();
        View view = LayoutInflater.from(context).inflate(R.layout.view_filter_layout, this);
        ButterKnife.bind(this, view);
        initView();
        initListener();
    }

    private void setData() {
        screenSelect.setVisibility(GONE);
        lvLeft.setVisibility(VISIBLE);
        List<String> stringList = new ArrayList<>();
        for (Map.Entry<String, String> entry : getSizeTaglist().entrySet()) {
            stringList.add((String) entry.getValue());
        }
        final List<String> getKey = new ArrayList<>();
        for (Map.Entry<String, String> entry : getSizeTaglist().entrySet()) {
            getKey.add((String) entry.getKey());
        }
        final ScreenAdapter arrayAdapter = new ScreenAdapter(stringList, mContext);
        lvLeft.setAdapter(arrayAdapter);
        arrayAdapter.notifyDataSetChanged();
        lvLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NetMsgEvent event = new NetMsgEvent();
                event.setErrorString(getKey.get(position));
                event.setMsgType(ON_ITEM_CLICK);
                EventbusHelper.post(event);
                tvHomeSalesVolume.setTextColor(mContext.getResources().getColor(R.color.font_black_5));
                tvHomeDistance.setTextColor(mContext.getResources().getColor(R.color.font_black_5));
                hide();
            }
        });
    }

    private void setDatas() {
        screenSelect.setVisibility(VISIBLE);
        lvLeft.setVisibility(GONE);
        mSizeTagAdapter = new TagAdapter<>(mContext);
        List<String> stringList = new ArrayList<>();
        for (Map.Entry<String, String> entry : getHistorylist().entrySet()) {
            stringList.add((String) entry.getValue());
        }
        getKey = new ArrayList<>();
        for (Map.Entry<String, String> entry : getHistorylist().entrySet()) {
            getKey.add((String) entry.getKey());
        }

        mSizeTagAdapter.onlyAddAll(stringList);
        mSizeFlowLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_NONE);
        mSizeFlowLayout.setAdapter(mSizeTagAdapter);
        mSizeTagAdapter.notifyDataSetChanged();
        mSizeFlowLayout.setOnTagSelectListener(this);
        mSizeFlowLayout.setOnTagClickListener(this);

        getKeytag2 = new ArrayList<>();
        for (Map.Entry<String, String> entry : getTag2list().entrySet()) {
            getKeytag2.add((String) entry.getKey());
        }
        List<String> tag2stringList = new ArrayList<>();
        for (Map.Entry<String, String> entry : getTag2list().entrySet()) {
            tag2stringList.add((String) entry.getValue());
        }
        tag2Adapter = new Tag2Adapter<>(mContext);
        tag2Adapter.onlyAddAll(tag2stringList);
        mHistoryFlowLayout.setOnTagSelectListener(this);
        mHistoryFlowLayout.setOnTagClickListener(this);
        mHistoryFlowLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_NONE);
        mHistoryFlowLayout.setAdapter(tag2Adapter);
        tag2Adapter.notifyDataSetChanged();
    }

    public static List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }

    @Override
    public void onItemSelect(FlowTagLayout parent, List<Integer> selectedList) {

    }


    @Override
    public void onItemClick(FlowTagLayout parent, View view, int position) {
        NetMsgEvent event = new NetMsgEvent();
        if (parent.getId() == R.id.size_flow_layout) {
            event.setErrorString(getKey.get(position));
            event.setMsgType(YOU_HUI_FILTER);
            EventbusHelper.post(event);
        } else if (parent.getId() == R.id.history_flow_layout) {
            event.setErrorString(getKeytag2.get(position));
            event.setMsgType(PEI_FILTER);
            EventbusHelper.post(event);
        }
        tvHomeSalesVolume.setTextColor(mContext.getResources().getColor(R.color.font_black_5));
        tvHomeDistance.setTextColor(mContext.getResources().getColor(R.color.font_black_5));
        hide();
    }


    private void initView() {
        viewMaskBg.setVisibility(GONE);
        llContentListView.setVisibility(GONE);
    }

    private void initListener() {
        viewMaskBg.setOnClickListener(this);
        tv_comprehensive.setOnClickListener(this);
        llContentListView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
    }

    // 复位筛选的显示状态
    public void resetViewStatus() {
        ivCategoryArrow.setImageResource(R.mipmap.home_nearby_synthesize_notclick);
    }

    // 复位所有的状态
    public void resetAllStatus() {
        resetViewStatus();
        hide();
    }

    // 旋转箭头向下
    private void rotateArrowDown(int position) {
        switch (position) {
            case POSITION_CATEGORY:
                rotateArrowDownAnimation(ivCategoryArrow);
                break;
            case POSITION_SORT:
                // rotateArrowDownAnimation(ivSortArrow);
                break;
            case POSITION_FILTER:
                //rotateArrowDownAnimation(ivFilterArrow);
                break;
        }
    }

    // 旋转箭头向上
    public static void rotateArrowUpAnimation(final ImageView iv) {
        if (iv == null) return;
        RotateAnimation animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(200);
        animation.setFillAfter(true);
        iv.startAnimation(animation);
    }

    // 旋转箭头向上
    private void rotateArrowUp(int position) {
        switch (position) {
            case POSITION_CATEGORY:
                rotateArrowUpAnimation(ivCategoryArrow);
                break;
            case POSITION_SORT:
                // rotateArrowUpAnimation(ivSortArrow);
                break;
            case POSITION_FILTER:
                //rotateArrowUpAnimation(ivFilterArrow);
                break;
        }
    }

    // 旋转箭头向下
    public static void rotateArrowDownAnimation(final ImageView iv) {
        if (iv == null) return;
        RotateAnimation animation = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(200);
        animation.setFillAfter(true);
        iv.startAnimation(animation);
    }
    // 是否显示

    public boolean isShowing() {
        return isShowing;
    }

    public int getFilterPosition() {
        return filterPosition;
    }

    // 动画显示
    public void show(int position) {
        screenPosition = position;
        if (isShowing && lastFilterPosition == position) {
            hide();
            return;
        } else if (!isShowing) {
            viewMaskBg.setVisibility(VISIBLE);
            llContentListView.setVisibility(VISIBLE);
            llContentListView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    llContentListView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    panelHeight = llContentListView.getHeight();
                    ObjectAnimator.ofFloat(llContentListView, "translationY", -panelHeight, 0).setDuration(200).start();
                }
            });
        }
        isShowing = true;
        resetViewStatus();
        rotateArrowUp(position);
        rotateArrowDown(lastFilterPosition);
        lastFilterPosition = position;
        switch (position) {
            case POSITION_CATEGORY:
                ivCategoryArrow.setImageResource(R.mipmap.home_nearby_synthesize_click);
                if (getSizeTaglist() != null)
                    setData();
                break;
            case POSITION_SORT:
                if (getHistorylist() != null)
                    setDatas();
                break;
            case POSITION_FILTER:
                break;
        }
    }

    // 隐藏动画
    public void hide() {
        isShowing = false;
        resetViewStatus();
        rotateArrowDown(filterPosition);
        rotateArrowDown(lastFilterPosition);
        filterPosition = -1;
        lastFilterPosition = -1;
        viewMaskBg.setVisibility(View.GONE);
        ObjectAnimator.ofFloat(llContentListView, "translationY", 0, -panelHeight).setDuration(200).start();
        llContentListView.setVisibility(GONE);
    }

    // 筛选视图点击
    private OnFilterClickListener onFilterClickListener;

    public void setOnFilterClickListener(OnFilterClickListener onFilterClickListener) {
        this.onFilterClickListener = onFilterClickListener;
    }


    public interface OnFilterClickListener {
        void onFilterClick(int position);
    }

    @OnClick({R.id.home_sales_volume, R.id.home_distance, R.id.home_screen, R.id.tv_clear, R.id.tv_affirm})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_clear:
                hide();
                break;
            case R.id.tv_affirm:
                hide();
                break;
            case R.id.view_mask_bg://关闭
                hide();
                NetMsgEvent event = new NetMsgEvent();
                event.setFlag(true);
                event.setStatusCode(10);
                event.setMsgType(HOMESCREEN);
                EventbusHelper.post(event);
                break;
            case R.id.home_sales_volume://销量
                hide();
                tvHomeSalesVolume.setTextColor(mContext.getResources().getColor(R.color.color_red));
                tvHomeDistance.setTextColor(mContext.getResources().getColor(R.color.font_black_5));
                NetMsgEvent event1 = new NetMsgEvent();
                event1.setMsgType(HOMESALESVOLUME);
                EventbusHelper.post(event1);
                break;
            case R.id.home_distance://距离
                hide();
                NetMsgEvent event2 = new NetMsgEvent();
                tvHomeDistance.setTextColor(mContext.getResources().getColor(R.color.color_red));
                tvHomeSalesVolume.setTextColor(mContext.getResources().getColor(R.color.font_black_5));
                event2.setMsgType(HOMEDISTANCE);
                EventbusHelper.post(event2);
                break;
            case R.id.home_screen://篩選
                hide();
                filterPosition = 1;
                if (onFilterClickListener != null) {
                    onFilterClickListener.onFilterClick(filterPosition);
                }
                NetMsgEvent event3 = new NetMsgEvent();
                event3.setFlag(isScreen);
                event3.setMsgType(HOMESCREEN);
                EventbusHelper.post(event3);
                break;
            case R.id.tv_comprehensive://排序
                hide();
                ivHomeScreen.setBackgroundDrawable(getResources().getDrawable(R.mipmap.home_nearby_filtrate_notclick));
                filterPosition = 0;
                if (onFilterClickListener != null) {
                    onFilterClickListener.onFilterClick(filterPosition);
                }
                break;
        }
    }
}
